package com.qjl.shopping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qjl.shopping.bean.User;
import com.qjl.shopping.common.Constants;
import com.qjl.shopping.controller.vm.UserVM;
import com.qjl.shopping.dao.UserMapper;
import com.qjl.shopping.exception.ServiceException;
import com.qjl.shopping.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author liguanghui
 * @Date 2023/5/1
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    /**
     * 注册
     * @param user
     * @return
     */
    @Override
    public int register(UserVM user) {
        System.out.println(user.getPwd());
        User u = new User();
        BeanUtils.copyProperties(user,u);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",user.getName());
        if (userMapper.selectList(queryWrapper).size()>0){
            throw new ServiceException(Constants.CODE_402,"用户名重复");
        }
        userMapper.insert(u);
        return 0;
    }

    /**
     * 登录
     * @param name
     * @param password
     * @return
     */
    @Override
    public UserVM login(String name, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_ac",name).eq("user_pwd",password);
        List<User> users = userMapper.selectList(queryWrapper);
        if(users.size()!=1){
            throw new ServiceException(400,"请确认账号或密码");
        }
        UserVM userVM = new UserVM();
        BeanUtils.copyProperties(users.get(0),userVM);
        return userVM;
    }

    @Override
    public Page<User> selectPage(int pageNum, int pageSize) {
        Page<User> page = new Page<>(pageNum,pageSize);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("user_id");
        Page selectPage = userMapper.selectPage(page, queryWrapper);
        return selectPage;
    }

    @Override
    public boolean updateById(User user) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());
        User user1 = userMapper.selectOne(queryWrapper);
        if(user1==null){
            throw new ServiceException(Constants.CODE_401,"无该user");
        }
        userMapper.updateById(user);
        return true;
    }
}
